#include <stdio.h>
#include <conio.h>
#include <signal.h>
#include <SMT.h>

static int flush = 0;
static int run = 1;

// myCallback will receive all events from the sensor
void myCallback(SMT_EVENT message, SMT_SENSOR sensor, SMT_CURSOR cursor)
{
	if (flush)
	{
		printf("\n");
		flush = 0;
	}
	
	// analyze message and print relevant information
	switch (message)
	{
	case SMT_SENSOR_CONNECT:
		SMT_DIMENSION window_dim, real_dim;
		SMT_GetSensorWindowDimension(sensor, &window_dim);
		SMT_GetSensorMatrixDimension(sensor, &real_dim);
		printf("Connected to sensor %d. Window : %dpx x %dpx. Physical : %dmm x %dmm\n", SMT_GetSensorID(sensor), window_dim.width, window_dim.height, real_dim.width, real_dim.height);
		break;
		
	case SMT_CURSOR_CREATE:
		printf("Cursor %d created\n", SMT_GetCursorID(cursor));
		break;
		
	case SMT_CURSOR_DOWN:
		printf("Cursor %d down at %d,%d \t(%d)\n", SMT_GetCursorID(cursor), SMT_GetCursorX(cursor), SMT_GetCursorY(cursor), SMT_GetCursorClickNbr(cursor));
		break;
		
	case SMT_CURSOR_MOVE:
		printf("Cursor %d move at %d,%d\n", SMT_GetCursorID(cursor), SMT_GetCursorX(cursor), SMT_GetCursorY(cursor));		
		break;
		
	case SMT_CURSOR_UP:
		printf("Cursor %d up at %d,%d\n", SMT_GetCursorID(cursor), SMT_GetCursorX(cursor), SMT_GetCursorY(cursor));		
		break;
		
	case SMT_CURSOR_DESTROY:
		printf("Cursor %d destroyed at %d,%d\n", SMT_GetCursorID(cursor), SMT_GetCursorX(cursor), SMT_GetCursorY(cursor));
		break;
		
	case SMT_SENSOR_DISCONNECT:
		printf("Disconnected from sensor %d\n", SMT_GetSensorID(sensor));
		break;

	default:
		break;
	}
}

void sigintHandler(int i)
{
	run = 0;
}

int main(int argc, char **argv)
{	
	// set up signal handler to exit cleanly
	signal(SIGINT, sigintHandler);
	signal(SIGTERM, sigintHandler);
	
	printf("opening connection to SMK...\n");
	// we call SMT_Open with a NULL ID to connect to the first SMK device detected
	// myCallback will be called for each event that occurs
	SMT_SENSOR s = SMT_Open(0, 800, 480, myCallback, 0);
	if (!s) 
	{
		// connection will fail if device is already connected to
		printf("failed opening connection to SMK\n");
		return 0;
	}

	printf("Move your fingers over the sensor and Press ESC to Quit\n");
	while (run)
	{
		// separate frames with blank new lines
		flush = 1;
		
		// call SMT_Update to receive new data from the SMK
		// SMT_Update will return 0 when connection is lost
		if (!SMT_Update(s))
		{
			run = 0;
		}

		if (kbhit() && getch()==0x1B)
		{
			run = 0;
		}
	}
	
	printf("closing connection to SMK...\n");
	// close connection to SMK before exit
	SMT_Close(s);
	return 0;
}
